package com.friends.utils.app;

import cn.hutool.core.util.RandomUtil;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * appId,appSecret 生成
 * @Author Zhao Tianhao
 * @Description
 * @Date 2024/7/19 14:31
 */
public class AppUtils {
	private final static String SERVER_NAME = "SYSTEM_CODE";

	/**
	 * 先构造一个十进制的数字,
	 * 前四位: 为随机值(1000,9999),
	 * 后13位: 为时间戳 (类似于这种形式1631238326627)
	 * 然后将该数字转换为字符串
	 * 再用36进制重新解析([0-9]|[a-z]), 数字和小写字母
	 * 得到的字符串长度为11个字节
	 *
	 * @return 生成的字符串用作app_id, 是个11个字节的字符串
	 */
	public static String genAppId() {
		final String s = RandomUtil.randomInt(1000, 9999) + String.valueOf(System.currentTimeMillis());
		BigInteger n = new BigInteger(s, 10);
		return n.toString(36);//转换成36进制, 得到的字符串长度11个字节
		//10000000000000000 转化之后是: 2qgpckvng1s ; 也是11个字节
		//99999999999999999 转化之后是: rcn1hssighr ; 也是11个字节
	}

	/**
	 * 通过appId和内置关键词生成APP Secret
	 */
	public static String genAppSecret(String appId) {
		try {
			String[] array = new String[]{appId, SERVER_NAME};
			StringBuffer sb = new StringBuffer();
			// 字符串排序
			Arrays.sort(array);
			for (int i = 0; i < array.length; i++) {
				sb.append(array[i]);
			}
			String str = sb.toString();
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			md.update(str.getBytes());
			byte[] digest = md.digest();

			StringBuffer hexstr = new StringBuffer();
			String shaHex = "";
			for (int i = 0; i < digest.length; i++) {
				shaHex = Integer.toHexString(digest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexstr.append(0);
				}
				hexstr.append(shaHex);
			}
			return hexstr.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
	}

	public static void main(String[] args) {
		String appId = genAppId();
		String appSecret = genAppSecret(appId);
		System.out.println("appId: "+appId);
		System.out.println("appSecret: "+appSecret);
	}
}
